#-*-coding:utf-8-*-

from celery import task
import paramiko



@task
def send_ras_key(path, hostname, port, username, password):
    f = open('%s/id_rsa.pub' % path, 'r')
    public_key = f.read()
    f.close()
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=hostname, port=port, username=username, password=password)
    cmd = 'cat /root/.ssh/authorized_keys | grep "%s" | wc -l' % public_key
    stdin, stdout, stderr = ssh.exec_command(cmd)
    res = stdout.read().strip()
    if res == '0':
        cmd = 'echo %s >> /root/.ssh/authorized_keys && chmod 600 /root/.ssh/authorized_keys' % public_key
        ssh.exec_command(cmd)
    ssh.close()